#!/usr/bin/env python
#
"""
Copyright (c) 2009 Twilio, Inc.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

__author__ = 'phy@twilio.com (Evan Cooke)'

import os, sys, re, urllib
import wsgiref.handlers
import twilio

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import mail

from twiliobot import BASE_URL
from voice import VoiceConnect

MY_NUMBER = "NNNNNNNNNN"
TWILIO_ACCOUNT_SID = 'ACXXX'
TWILIO_ACCOUNT_TOKEN = 'YYY'

class CallStartPage(webapp.RequestHandler):
    """click to call handler class"""
    
    def get(self):
        self.post()
    
    def post(self):
        """
        WARNING: this code is for demonstration purproses only.  Another
        http client beside Wave could trigger this URL resulting in a call
        which could be abused.  
        """
        if not self.request.get("number"):
            return self.response.out.write("must specify 'number' param")
        
        # create a twilio account object
        account = twilio.Account(TWILIO_ACCOUNT_SID, TWILIO_ACCOUNT_TOKEN)
        
        # fire off the phone call using twilio REST API
        d = {"number": self.request.get("number")}
        account.initiate_call(MY_NUMBER,
            BASE_URL + '/twiml/connect?' + urllib.urlencode(d),
            caller=MY_NUMBER)
        self.response.out.write("calling you then " + \
            self.request.get("number"))

def main():
    application = webapp.WSGIApplication([ \
        ('/callstart', CallStartPage),
        ('/twiml/connect', VoiceConnect)],
        debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
